﻿using Microsoft.AspNetCore.Http;

namespace Infrastructure.Helper
{
    public static class CookieHelper
    {
        /// <summary>
        /// 将值写入 Cookie
        /// </summary>
        /// <param name="HttpContext">HTTP 上下文</param>
        /// <param name="Key">Cookie 键名</param>
        /// <param name="Value">Cookie 值</param>
        /// <param name="ExpTimeSec">过期时间（秒），默认为 3600 秒（1 小时）</param>
        public static void WriteCookie(this HttpContext HttpContext, string Key, string Value, int ExpTimeSec = 3600)
        {
            string host = HttpContext.Request.Host.Host;
            string domain;
            try
            {
                // 获取域名的顶级域
                domain = ((host.Split(".").Length <= 1) ? host : string.Join('.', host.Split(".")[^2..]));
            }
            catch (Exception)
            {
                domain = host;
            }

            CookieOptions options = new CookieOptions
            {
                Expires = DateTime.Now.AddSeconds(ExpTimeSec),
                Path = "/",
                Domain = domain
            };
            HttpContext.Response.Cookies.Append(Key, Value, options);
        }

        /// <summary>
        /// 从 Cookie 中读取值
        /// </summary>
        /// <param name="HttpContext">HTTP 上下文</param>
        /// <param name="strName">Cookie 名称</param>
        /// <returns>Cookie 值，若不存在则返回空字符串</returns>
        public static string ReadCookie(this HttpContext HttpContext, string strName)
        {
            return HttpContext.Request.Cookies[strName] ?? "";
        }

        /// <summary>
        /// 从请求头中读取值
        /// </summary>
        /// <param name="HttpContext">HTTP 上下文</param>
        /// <param name="strName">头部名称</param>
        /// <returns>头部值，若不存在则返回空字符串</returns>
        public static string ReadHeader(this HttpContext HttpContext, string strName)
        {
            return HttpContext.Request.Headers[strName].ToString() ?? "";
        }

        /// <summary>
        /// 将值写入请求头
        /// </summary>
        /// <param name="HttpContext">HTTP 上下文</param>
        /// <param name="strName">头部名称</param>
        /// <param name="Value">头部值</param>
        public static void WriteHeader(this HttpContext HttpContext, string strName, string Value)
        {
            HttpContext.Request.Headers.Add(strName, Value);
        }

        /// <summary>
        /// 清除指定名称的 Cookie
        /// </summary>
        /// <param name="HttpContext">HTTP 上下文</param>
        /// <param name="strName">Cookie 名称</param>
        /// <returns>清除成功返回 true，失败返回 false</returns>
        public static bool ClearCookie(this HttpContext HttpContext, string strName)
        {
            try
            {
                HttpContext.Response.Cookies.Delete(strName);
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
